import * as React from "react";
import { inject, observer } from "mobx-react";
import { Form, Icon, Input, Button, Checkbox, message, Modal } from 'antd';
import { WrappedFormUtils } from 'antd/lib/form/Form';
import { LoginStore } from "../../../store";
import ls from '../../../util/localStorage';
import { login, userInfo, forgetPassword } from '../../../basicData/api'
import { History } from 'history';
import { CommonData } from '../../../basicData/data'

import '../login.less';

const FormItem = Form.Item;

interface IProps {
  history: History;
  loginStore?: LoginStore;
  children?: AudioContextLatencyCategory;
  form: WrappedFormUtils;
}

@inject("loginStore")
@observer
class LoginForm extends React.Component<IProps, {}> {

  componentDidMount() {
    const isRemember = ls.get('remember');
    const token = ls.get('token');
    if(token)
      ls.remove('token')
    if (isRemember) {
      const username = ls.get('username');
      this.props.form.setFieldsValue({ username })
    }
  }

  handleSubmit = (e: React.FormEvent<any>) => {
    e.preventDefault();
    const _this = this;
    
    this.props.form.validateFields((
      err: Error | null,
      values: { username: string, password: string, remember: boolean }
    ) => {
      if (!err) {
        if (values.remember) {
          ls.set('remember', values.remember);
          ls.set('username', values.username);
        } else {
          ls.remove(['remember', 'username',])
        }
        if(values.password) {
          const param = {
            client_id: 'Hicap.Application',
            // client_id: 'Hicap.QRCodeWarehouse',
            // client_secret: 'HicapMES_C421AAEE0D114E9C',
            // client_secret: 'HicapApplication_C421AAEE0D114E9C',
            client_secret: 'HicapApplication_DF64402325E34B398F0A8ED1CCEA65AE',
            // client_secret: 'Hicap~!@#$%^&*()',
            grant_type: 'password',
            username: values.username,
            password: values.password
          }
          login(param).then((res: any) => {
            let _window: any = window;
            _window.frames[0].postMessage(res.data.access_token, `${CommonData.QRCodeURL[process.env.NODE_ENV]}/`);
            ls.set('token', res.data.access_token)
            ls.set('loginTime', new Date().getTime())
            ls.set('effectiveTime', res.data.expires_in)
            let href = ls.get('href')
            if(href) {
              ls.remove('href')
              window.location.href = href
            }
            this.props.history.push('/home');
            this.props.history.go(0);
          })
        } else {
          message.error('请输入密码')
        }
      }
    });
  }

  register = () => {
    this.props.loginStore.register(true)
  }

  forgetPwd = () => {
    this.props.form.validateFields((
      err: Error | null,
      values: { username: string, password: string, remember: boolean }
    ) => {
      if (!err) {
        forgetPassword(values.username).then((res: any) => {
          if(res.success) {
            Modal.success({
              title: '操作成功',
              content: '已通知管理员重置密码'
            })
          }
        })
        
      }
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
    };

    return (
      <Form onSubmit={this.handleSubmit} className="login-form">
        <h2>欢迎登录系统</h2>
        <FormItem {...formItemLayout} label="用户名">
          {getFieldDecorator('username', {
            rules: [{ required: true, message: '请输入用户名!' }],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="用户名"
            />
          )}
        </FormItem>
        <FormItem {...formItemLayout} label="密   码">
          {getFieldDecorator('password', {
            rules: [{ required: false, message: '请输入密码!' }],
          })(
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="密码"
            />
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('remember', {
            valuePropName: 'checked',
            initialValue: true,
          })(
            <Checkbox>记住我</Checkbox>
          )}
          <a className="login-form-forgot" onClick={this.forgetPwd}>忘记密码</a>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登录
          </Button>
          <span>没有账号？ <a onClick={this.register}>立即注册</a></span>
        </FormItem>
      </Form>
    );
  }
}

export default Form.create()(LoginForm)